java线程死锁原因及避免

死锁原因

        线程死锁的本质在于不同线程对资源锁的竞争,如果竞争中存在闭环,则会出现死锁。而为了避免死锁,最关键的是避免出现资源锁竞争的闭环。

避免死锁的秘诀

        资源按顺序调用。

理解

        1、资源指的是需要加锁的对象,不加锁就不存在竞争,也就谈不上资源的死锁。2、不同线程在调用资源时,均需按相同的顺序调用资源。

示例

       以下的示例只要testSynchronized方法传入的资源顺序相同,即不可能出现死锁,顺序不同则会死锁。

public class MainTest {
    public static void main(String[] args) {
        MainTest mainTest = new MainTest();

        String[] a = new String[4];
        String[] b = new String[4];

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                mainTest.testSychronized(a, b);
            }
        });
        thread.setName("T-A");
        thread.start();

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                mainTest.testSychronized(b, a);
            }
        });
        thread2.setName("T-B");
        thread2.start();
    }

    private void testSychronized(String[] a, String[] b) {
        for (int i = 0; i < 1000; i++) {
            synchronized (a) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (b) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println(Thread.currentThread().getName());
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值